<?php

/**
 * @author ducnhat
 * @email ddnhat@gmail.com
 * @copyright 2014
 */

class Admin_Model_Taxonomy extends Zend_Db_Table{
	
	protected $_name    = "taxonomy";
    protected $_primary = "id";
    
    public function saveData($data = array()){
    	$db = Zend_Registry::get('db');
        
        $db->beginTransaction();
        
        try{
            if(isset($data['id']) && $this->checkExists($data['id'])){
                $id = $data['id'];
                $db->update("taxonomy", $data, "id = $id");
            }else{
                $db->insert('taxonomy', $data);
            }
            
            $cache = new Zenddn_System_Cache();
            $cache->clean(array('taxonomy'));
            
            $db->commit();
            
            return true;
        }catch(Exception $e){
            $db->rollBack();
            
            return false;
        }
    }
    
    public function getData($type = null, $id = null){
    	$db = Zend_Registry::get('db');
        $db->setFetchMode(Zend_Db::FETCH_OBJ);
        
        $select = $db->select()
                    ->from(array('t' => 'taxonomy'), array('id', 'name', 'type'))
                    ->order('t.id DESC');
        
        if($type != null){
            $select->where("t.type = ?", $type);
        }
        
        if($id != null){
            $select->where("t.id = ?", $id, 'INTEGER');
            
            $db->setFetchMode(Zend_Db::FETCH_ASSOC);
            $result = $db->fetchRow($select);
        }else{
            $result = $db->fetchAll($select);
        }
        
        return $result;
    }
    
    public function getAllData($type = null){
    	return $this->getData($type);
    }
    
    public function deleteData($id){
    	$db = Zend_Registry::get('db');
        
        $db->beginTransaction();
        
        try{
            $db->delete('taxonomy', "id = $id");
            
            $cache = new Zenddn_System_Cache();
            $cache->clean(array('taxonomy'));
            
            $db->commit();
            
            return true;
        }catch(Exception $e){
            $db->rollBack();
            
            return false;
        }
    }
    
    public function checkExists($id){
        $option = array('table' => 'taxonomy', 'field' => 'id');
    	$validator = new Zend_Validate_Db_RecordExists($option);
        
        if($validator->isValid($id)){
            return true;
        }
        
        return false;
    }
}